﻿using AutoMapper;
using B.S.RbacData.Domain.Traceabilitys;
using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using B.S.RbacData.Read.API.Applications.Commands.Traceabilitys;
using B.S.RbacData.Read.API.Dtos.Traceabilitys;
using MediatR;

namespace B.S.RbacData.Read.API.Applications.CommandHandlters.Traceabilitys
{
    /// <summary>
    /// 产品详情命令处理
    /// </summary>
    public class GetEnditCommandhandlter : IRequestHandler<GetEnditCommand, ApiResult<GetEnditDtos>>
    {
        /// <summary>
        /// 产品信息
        /// </summary>
        private readonly IBaseRepository<ProductModel> productRep;
        /// <summary>
        /// 商品信息
        /// </summary>
        private readonly IBaseRepository<GoodsModel> goodsRep;
        /// <summary>
        /// 映射
        /// </summary>
        private readonly IMapper mapper;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="productRep">产品信息</param>
        /// <param name="goodsRep">商品信息</param>
        public GetEnditCommandhandlter(IBaseRepository<ProductModel> productRep, IBaseRepository<GoodsModel> goodsRep,IMapper mapper)
        {
            this.productRep = productRep;
            this.goodsRep = goodsRep;
            this.mapper = mapper;
        }


        public async Task<ApiResult<GetEnditDtos>> Handle(GetEnditCommand request, CancellationToken cancellationToken)
        {

            //根据产品编号查询产品
            var product=productRep.GetAll().FirstOrDefault(x=>x.ID==request.ProductId);
            if(product==null)
            {

                return new ApiResult<GetEnditDtos>
                {

                    code = ResultEnumCode.fails,
                    data = null,
                    message = "获取失败"

                };

            }
            //获取商品名称
            var goodsname = goodsRep.GetAll().FirstOrDefault(x=>x.ID== product.GoodsId)?.GoodsName;

            var getdtos = mapper.Map<GetEnditDtos>(product);
            getdtos.GoodsName = goodsname??"";


            return new ApiResult<GetEnditDtos>
            {

                code = ResultEnumCode.Ok,
                data = getdtos,
                message = "获取成功"

            };
        }
    }
}
